/*=============================================================================
Copyright (c) 2005 AUTOMATED LOGIC CORPORATION

This file is part of DominoTomcatSSOIntegration.
http://www.automatedlogic.com/domblog.nsf/dx/DominoTomcatSSOIntegration

DominoTomcatSSOIntegration is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

DominoTomcatSSOIntegration is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
http://www.gnu.org/licenses/gpl.html
=============================================================================*/

package com.automatedlogic.domino.sso.login;

import com.automatedlogic.domino.sso.DominoUserProfile;
import com.automatedlogic.domino.sso.LtpaToken;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Creates a new LtpaToken cookie for the web user.
 *
 * @author Brian Green, Automated Logic Corporation
 * @version 2.4.3, Feb 25 2005
 * @see <a href="http://www.automatedlogic.com/domblog.nsf/dx/DominoTomcatSSOIntegration">Automated Logic Corporation</a>
 * @since JDK1.4.2_06
 */
public class DominoLoginServlet extends HttpServlet implements DominoLoginConstants {

    private HttpSession session;
    private HttpServletRequest request;
    private HttpServletResponse response;

    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        doPost(httpServletRequest, httpServletResponse);
    }

    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        request = httpServletRequest;
        response = httpServletResponse;
        session = request.getSession();

        login();
    }


    private void login() throws IOException, ServletException {

        //Get the debug value.  Optional.  This is defined in web.xml.
        String debug = getServletConfig().getInitParameter(DOMINO_TOMCAT_LOGIN_DEBUG) == null ? "" : getServletConfig().getInitParameter(DOMINO_TOMCAT_LOGIN_DEBUG);

        //Get the location of the Domino server.  Required.  This is defined in web.xml.
        String dominoServer = getServletConfig().getInitParameter(DOMINO_DIIOP_CONNECTION) == null ? "" : getServletConfig().getInitParameter(DOMINO_DIIOP_CONNECTION);
        if (dominoServer.equals("")) {
            logMessage(debug, MSG_DOMINO_DIIOP_CONNECTION_NOT_DEFINED);
            response.setContentType("text/html");
            response.getWriter().println(MSG_DOMINO_DIIOP_CONNECTION_NOT_DEFINED);
            return;
        }

        //Get the LTPA_TOKEN_COOKIE_DOMAIN preference.  Required.  This is defined in web.xml.
        String ltpaTokenCookieDomain = getServletConfig().getInitParameter(LTPA_TOKEN_COOKIE_DOMAIN) == null ? "" : getServletConfig().getInitParameter(LTPA_TOKEN_COOKIE_DOMAIN);
        if (ltpaTokenCookieDomain.equals("")) {
            logMessage(debug, MSG_LTPA_TOKEN_COOKIE_DOMAIN_NOT_DEFINED);
            response.setContentType("text/html");
            response.getWriter().println(MSG_LTPA_TOKEN_COOKIE_DOMAIN_NOT_DEFINED);
            return;
        }

        //Get the username and password from the login form.
        String username = getLoginFormData(request, "Username", "");
        String password = getLoginFormData(request, "Password", "");
        String redirectto = getLoginFormData(request, "RedirectTo", "/");
        //eqe
        request.getSession().setAttribute("uname", username);
        request.getSession().setAttribute("pword",password);
        request.getSession().setAttribute("redirto",redirectto);
        //eqe
        //Create a LtpaToken for this username and password.
        LtpaToken token = new LtpaToken(dominoServer, username, password);

        //Create a Cookie for the web browser.  This is added to the HttpServletResponse.
        boolean success;
        success = token.setCookie(response, ltpaTokenCookieDomain);


        //Is the LtpaToken valid?
        if (success) {

            //Remove the DominoLoginFailure object in the user's session, if it exists.
            DominoLoginFailure dominoLoginFailure = (DominoLoginFailure) session.getAttribute("DominoLoginFailure");
            if (dominoLoginFailure != null) {
                session.removeAttribute("DominoLoginFailure");
            }
            //Redirect the user to the requested web page.
            logMessage(debug, "Hello " + username + " - Redirecting to " + redirectto);
            response.sendRedirect(redirectto);
          //  getServletContext().getNamedDispatcher(response.encodeRedirectURL(redirectto)).forward(request,response);
            

        } else {
            //Otherwise, redirect the user to the login page again.

            //Create or Update the DominoLoginFailure object in the user's session.  You can reference these
            //properties on your login.jsp page: dominoErrorText, dominoErrorID
            DominoLoginFailure dominoLoginFailure = (DominoLoginFailure) session.getAttribute("DominoLoginFailure");
            if (dominoLoginFailure == null) {
                dominoLoginFailure = new DominoLoginFailure(token.dominoErrorID, token.dominoErrorText);
            } else {
                dominoLoginFailure.setDominoErrorID(token.dominoErrorID);
                dominoLoginFailure.setDominoErrorText(token.dominoErrorText);
            }
            session.setAttribute("DominoLoginFailure", dominoLoginFailure);

            //Redirect to the login page.
            String referer = request.getHeader("Referer");
            logMessage(debug, "Login failed for " + username + " - Redirecting to " + referer);
            response.sendRedirect(referer);
        }

    }


    /**
     * @param request      HttpServletRequest
     * @param fieldname    The name of a field on the Login form.
     * @param defaultValue If the fieldname is not found on the login form, or the value is empty, returns the default value.
     * @return Returns      The value of the form's field, or the default value.
     */
    private String getLoginFormData(HttpServletRequest request, String fieldname, String defaultValue) {
        String result;

        //The login form should contain the fieldname.  Because field names are case-sensitive,
        //we check for the fieldname, and also the lowercase of fieldname.
        result = request.getParameter(fieldname);
        if (result == null) {
            result = request.getParameter(fieldname.toLowerCase());
        }

        //If the value is null or blank, set it to the defaultValue.
        if (result == null) {
            result = defaultValue;
        }
        if (result.equals("")) {
            result = defaultValue;
        }

        return result;
    }


    /**
     * Print a message to the log file.
     *
     * @param debug   Message is printed when this value is "1".
     * @param message The message to print.
     */
    private void logMessage(String debug, String message) {
        if (debug.equals("1")) {
            session.getServletContext().log(" " + message);
        }
    }


}
